package net.zoneland.zoneapp.tree;

import java.util.List;
import java.util.Random;

import net.zoneland.zoneapp.R;
import net.zoneland.zoneapp.common.tree.Node;
import net.zoneland.zoneapp.common.tree.TreeHelper;
import net.zoneland.zoneapp.common.tree.TreeListViewAdapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 *
 * @author FancyLou
 * @date 2015年4月21日 下午10:54:07
 *
 * @param <T>
 */
public class SimpleTreeListViewAdapter<T> extends TreeListViewAdapter<T> {
	/**
	 * 构造
	 *
	 * @param tree
	 * @param context
	 * @param datas
	 * @param defaultExpandLevel
	 * @throws IllegalAccessException
	 */
	public SimpleTreeListViewAdapter(ListView tree, Context context,
			List<T> datas, int defaultExpandLevel)
			throws IllegalAccessException {
		super(tree, context, datas, defaultExpandLevel);
	}

	@SuppressWarnings("unchecked")
	@Override
	public View getConvertView(Node node, int position, View convertView,
			ViewGroup viewGroup) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.tree_list_item, viewGroup,
					false);
			holder = new ViewHolder();
			holder.treeItemIcon = (ImageView) convertView
					.findViewById(R.id.id_tree_item_icon);
			holder.treeItemText = (TextView) convertView
					.findViewById(R.id.id_tree_item_text);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		if (node.isLeaf()) {
			holder.treeItemIcon.setVisibility(View.INVISIBLE);
		} else {
			holder.treeItemIcon.setVisibility(View.VISIBLE);
			holder.treeItemIcon.setImageResource(node.getIcon());
		}
		holder.treeItemText.setText(node.getName());

		return convertView;
	}

	private class ViewHolder {
		ImageView treeItemIcon;
		TextView treeItemText;
	}

	/**
	 * 动态插入节点
	 * 
	 * @param position
	 * @param name
	 */
	public void addExtraNode(int position, String name) {
		Node node = visibleNodes.get(position);
		int indexOf = allNodes.indexOf(node);

		// 保持node
		Random r = new Random();
		int i = 10 * r.nextInt(10);
		Node extraNode = new Node(i, node.getId(), name);
		extraNode.setParent(node);
		node.getChildren().add(extraNode);
		allNodes.add(indexOf + 1, extraNode);
		visibleNodes = TreeHelper.filterVisibleNodes(allNodes);
		notifyDataSetChanged();
	}

}
